package xyz.zhzby.cyzx.oj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.ApiOperation;
import xyz.zhzby.cyzx.oj.convert.CategoryConvert;
import xyz.zhzby.cyzx.oj.dto.response.CategoryResponse;
import xyz.zhzby.cyzx.oj.dto.response.Info;
import xyz.zhzby.cyzx.oj.entity.Category;
import xyz.zhzby.cyzx.oj.mapper.CategoryMapper;
import xyz.zhzby.cyzx.oj.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.zhzby.cyzx.security.entity.User;
import xyz.zhzby.cyzx.security.util.CyzxSecurityContextHolder;
import xyz.zhzby.cyzx.servicebase.domain.DataLogInfo;
import xyz.zhzby.cyzx.servicebase.domain.RestResponse;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 试题分类 服务实现类
 * </p>
 *
 * @author zby
 * @since 2021-12-26
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Override
    public RestResponse<String> createCategory(String categoryName) {
        User subject = CyzxSecurityContextHolder.getSubject();
        Category category = new Category();
        category.setName(categoryName);
        subject.fillCreateInfo(category, DataLogInfo.USER_FIELD_ACTUAL_NAME);
        baseMapper.insert(category);
        return RestResponse.success("创建成功");
    }

    @Override
    public RestResponse<List<CategoryResponse>> getAllCategorys() {
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.orderByAsc(Category::getId);
        List<Category> categories = baseMapper.selectList(qw);
        List<CategoryResponse> categoryResponses = build(categories);
        return RestResponse.success(categoryResponses);
    }

    @ApiOperation("使用递归方法建试题分类列表")
    private static List<CategoryResponse> build(List<Category> treeNodes) {
        List<CategoryResponse> trees = new ArrayList<>();
        for (Category treeNode : treeNodes) {
            if (treeNode.getParentId().equals(0L)) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    @ApiOperation("递归查找子节点")
    private static CategoryResponse findChildren(Category treeNode, List<Category> treeNodes) {
        CategoryResponse res = new CategoryResponse();
        res.setValue(treeNode.getId());
        res.setLabel(treeNode.getName());
        res.setChildren(new ArrayList<>());

        for (Category node : treeNodes) {
            if (treeNode.getId().equals(node.getParentId())) {
                res.getChildren().add(findChildren(node, treeNodes));
            }
        }
        if (res.getChildren().isEmpty()) {
            res.setChildren(null);
        }
        return res;
    }

    @Override
    public List<Info> getLinkCategorysByProblemID(Long problemID) {
        return baseMapper.getLinkCategorysByProblemID(problemID);
    }
}
